--global string containing all registered formspec pages as table data
ezformmaker = {
  pages = {},
  
  --Set String for Form's Context
  set_string = function(self, string, value)
    self[string] = value
  end,
  
    --Get String for Form's Context
  get_string = function(self, string)
    return self[string]
  end

}

--Register a new form page
function ezformmaker.register_form_page(formname, def)

  local name_convention_check = string.match(formname, "[%w_]+%:[%w_]+")

  assert(formname, "Formspec requires a name.")
  assert(name_convention_check, "Name \""..formname.."\" does not follow naming conventions: \"<foo>:<bar>\" or \":\" prefix required.")
  assert(def, "attempt to index local def a nil value for formspec \""..formname.."\".")
  assert(def.on_send_form, "def requires method \"on_send_form\" for formspec \""..formname.."\".")
  assert(def.on_receive_fields, "def requires method \"on_receive_fields\" for formspec \""..formname.."\".")
  assert(not ezformmaker.pages[formname], "attempt to register a form page that already exist. " .. dump(formname))

  ezformmaker.pages[formname] = def
  def.name = formname
end

--Show specific formpage to a player by name
function ezformmaker.show_form_page(name, formname)

  -- Cancel function if something went wrong and write a error log explaining what happened
  if minetest.get_player_by_name(name) == nil then
    minetest.log("error", "Failed to send form to specified player, player \""..name.."\" is not online.")
    return
  elseif ezformmaker.pages[formname] == nil then
    minetest.log("error", "Invalid form page, formspec \""..formname.."\" doesn\'t exist.")
    return
  end

  local player = minetest.get_player_by_name(name)
  local form = ezformmaker.pages[formname].on_send_form(player)

  minetest.show_formspec(name, formname, form)
end


--Input Event Handler
minetest.register_on_player_receive_fields(function(player, formname, fields)

  --Don't do anything if fields are empty
  if fields == nil then
    return
  end

  local name = player:get_player_name()
  local verified_form = nil
  local pages = ezformmaker.pages
  local page = nil

  if pages == nil then return else
    for k,v in pairs(pages) do
      if k == formname then
        verified_form = k
        page = ezformmaker.pages[formname]
        break
      end
    end
  end

  if verified_form == nil then
    return
  elseif verified_form == formname then

    --If form page exists, make sure to run it's unique recieve fields script
    return page.on_receive_fields(player, formname, fields)
  end

end)